package org.atlantis.ymer.common;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelFutureListener;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.jboss.netty.handler.codec.http.HttpVersion;
import org.jboss.netty.util.CharsetUtil;

public abstract class HttpResponseUtils {

	public static final String CONTENT_TYPE_HTML = "text/html; charset=UTF-8";
	public static final String CONTENT_TYPE_JSON = "application/json";
	// contentType应该是：application/javascript，但是多数老浏览器不支持
	public static final String CONTENT_TYPE_JAVASCRIPT = "text/javascript";

	private static final String FORBIDDEN_TEXT = "You are Forbidden!";
	private static final String BADRUEST_TEXT = "Bad Request!";

	public static final String CROSS_DOMAIN_ORIGIN = "Access-Control-Allow-Origin";
	public static final String CROSS_DOMAIN_METHOD = "Access-Control-Allow-Methods";
	public static final String CROSS_DOMAIN_HEADER = "Access-Control-Allow-Headers";

	private static void sendBadHttpResponse(Channel channel, HttpRequest request, String text) {
		HttpResponse response = createCrossDomainHeaderResponse();
		response.setContent(ChannelBuffers.copiedBuffer(text, CharsetUtil.UTF_8));
		response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
		HttpHeaders.setContentLength(response, response.getContent().readableBytes());
		ChannelFuture future = channel.write(response);
		if (HttpHeaders.isKeepAlive(request)) future.addListener(ChannelFutureListener.CLOSE);
	}

	public static void sendForbiddenHttpResponse(Channel channel, HttpRequest request) {
		sendBadHttpResponse(channel, request, FORBIDDEN_TEXT);
	}

	public static void sendBadRequestHttpResponse(Channel channel, HttpRequest request) {
		sendBadHttpResponse(channel, request, BADRUEST_TEXT);
	}

	public static HttpResponse createCrossDomainHeaderResponse() {
		HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
		response.setHeader(HttpHeaders.Names.CACHE_CONTROL, HttpHeaders.Values.NO_CACHE);
		response.addHeader(CROSS_DOMAIN_ORIGIN, "*");
		return response;
	}
}
